package com.guet.controller.common;

import com.guet.result.Result;
import com.guet.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController("studentCommonController")
@RequestMapping("/student/common")
@Slf4j
@CrossOrigin
public class StuCommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    public StuCommonController(AliOssUtil aliOssUtil) {
        this.aliOssUtil = aliOssUtil;
    }

    @PostMapping("upload")
    // 前端传过来的是MultipartFile格式，Spring可以直接处理这种格式
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传{}", file);
        // 获取文件的原始完整名字
        String originalFilename = file.getOriginalFilename();
        // 获取文件的格式名，比如.jpg,.png等
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 使用UUID生成唯一的标识符，为了防止文件重名，并且加上文件件格式
        String objectName = UUID.randomUUID().toString() + extension;
        try {
            // 调用upload方法，传入MultipartFile格式的文件和文件名称
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败{}", e);
        }
        return null;
    }
}
